/*******************************************************************************
 * Copyright (c) 2011 TXT e-solutions SpA
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * This work was performed within the IoT_at_Work Project
 * and partially funded by the European Commission's
 * 7th Framework Programme under the research area ICT-2009.1.3
 * Internet of Things and enterprise environments.
 *
 *
 * Authors:
 *     Cristoforo Seccia (TXT e-solutions SpA)
 *
 * Contributors:
 *      Domenico Rotondi (TXT e-solutions SpA)
 *******************************************************************************/
package it.txt.access.capability.wizard.panel;

import it.txt.access.capability.commons.filter.FilterJKS;
import it.txt.access.capability.wizard.panel.controller.ControllerPanelKeystore;
import java.awt.Frame;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

/**
 *
 * @author Cristoforo Seccia (TXT e-solutions SpA)
 */
public class PanelKeystore extends javax.swing.JPanel {

    private File currentKeystoreDirecotory = null;
    private ControllerPanelKeystore controller;
    private boolean isCertificatePswOk = false;
    private boolean isKeystorePathOk = false;
    private boolean isKeystorePswOPk = false;
    private FilterJKS filterKeystore;
    private JFileChooser keystoreChooser;
    private Frame myContainer;

    /** Creates new form PanelWelcome */
    public PanelKeystore(Frame container, ControllerPanelKeystore cpw) {
        initComponents();
        checkKeystorePathDocument();
        checkKeystorePasswordDocument();
        checkCertificatePasswordDocument();
        controller = cpw;
        myContainer = container;
        filterKeystore = new FilterJKS();
        keystoreChooser = new JFileChooser();
        keystoreChooser.setFileFilter(filterKeystore);
        keystoreChooser.setMultiSelectionEnabled(false);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        centerPanel = new javax.swing.JPanel();
        centerTitlePanel = new javax.swing.JPanel();
        jSeparator1 = new javax.swing.JSeparator();
        welcomeLabel = new javax.swing.JLabel();
        keystorePathLabel = new javax.swing.JLabel();
        keystorePswLabel = new javax.swing.JLabel();
        keystorePswText = new javax.swing.JPasswordField();
        keystorePathText = new javax.swing.JTextField();
        keystorePathButton = new javax.swing.JButton();
        keystoreNoteslabel = new javax.swing.JLabel();
        jSeparator2 = new javax.swing.JSeparator();
        jPanel1 = new javax.swing.JPanel();
        policyGetCertificateButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        keystoreNotesArea = new javax.swing.JTextArea();
        certificatePswLabel = new javax.swing.JLabel();
        certificatePswText = new javax.swing.JPasswordField();

        centerPanel.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));

        centerTitlePanel.setBorder(javax.swing.BorderFactory.createTitledBorder("IoT@Work - Capability Based Authorization"));

        welcomeLabel.setText("Certificate Keystore");

        keystorePathLabel.setText("Keystore path *");

        keystorePswLabel.setText("Keystore password *");

        keystorePswText.setToolTipText("Please inserte your Java keystore password");
        keystorePswText.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 0, 0)));

        keystorePathText.setToolTipText("Please insert your Java Keystore path");
        keystorePathText.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 0, 0)));

        keystorePathButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icons_16x16/Open_16x16.png"))); // NOI18N
        keystorePathButton.setText("Open");
        keystorePathButton.setToolTipText("Open your certificate keystore.");
        keystorePathButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                keystorePathButtonActionPerformed(evt);
            }
        });

        keystoreNoteslabel.setText("Notes");

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        policyGetCertificateButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icons_24x24/Certificate_24x24.gif"))); // NOI18N
        policyGetCertificateButton.setText("Get Certificate");
        policyGetCertificateButton.setEnabled(false);
        policyGetCertificateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                policyGetCertificateButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(254, Short.MAX_VALUE)
                .addComponent(policyGetCertificateButton)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(policyGetCertificateButton)
                .addContainerGap())
        );

        keystoreNotesArea.setColumns(20);
        keystoreNotesArea.setEditable(false);
        keystoreNotesArea.setFont(new java.awt.Font("Monospaced", 1, 14));
        keystoreNotesArea.setRows(5);
        jScrollPane1.setViewportView(keystoreNotesArea);

        certificatePswLabel.setText("Certificate password *");

        certificatePswText.setToolTipText("Please inserte your Certificate password");
        certificatePswText.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 0, 0)));

        javax.swing.GroupLayout centerTitlePanelLayout = new javax.swing.GroupLayout(centerTitlePanel);
        centerTitlePanel.setLayout(centerTitlePanelLayout);
        centerTitlePanelLayout.setHorizontalGroup(
            centerTitlePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, centerTitlePanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(centerTitlePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(welcomeLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 407, Short.MAX_VALUE)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 407, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, centerTitlePanelLayout.createSequentialGroup()
                        .addGroup(centerTitlePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(certificatePswLabel)
                            .addComponent(keystorePswLabel)
                            .addComponent(keystorePathLabel))
                        .addGap(18, 18, 18)
                        .addGroup(centerTitlePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, centerTitlePanelLayout.createSequentialGroup()
                                .addComponent(keystorePathText, javax.swing.GroupLayout.DEFAULT_SIZE, 184, Short.MAX_VALUE)
                                .addGap(18, 18, 18)
                                .addComponent(keystorePathButton))
                            .addComponent(keystorePswText, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 281, Short.MAX_VALUE)
                            .addComponent(certificatePswText, javax.swing.GroupLayout.DEFAULT_SIZE, 281, Short.MAX_VALUE)))
                    .addComponent(keystoreNoteslabel, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 407, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 407, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        centerTitlePanelLayout.setVerticalGroup(
            centerTitlePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(centerTitlePanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(welcomeLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(centerTitlePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(keystorePathLabel)
                    .addComponent(keystorePathText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(keystorePathButton))
                .addGap(18, 18, 18)
                .addGroup(centerTitlePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(keystorePswLabel)
                    .addComponent(keystorePswText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(centerTitlePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(certificatePswLabel)
                    .addComponent(certificatePswText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(keystoreNoteslabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 123, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout centerPanelLayout = new javax.swing.GroupLayout(centerPanel);
        centerPanel.setLayout(centerPanelLayout);
        centerPanelLayout.setHorizontalGroup(
            centerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(centerPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(centerTitlePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        centerPanelLayout.setVerticalGroup(
            centerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(centerPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(centerTitlePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(centerPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(centerPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    private void keystorePathButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_keystorePathButtonActionPerformed
        handleKeystorePathButtonActionPerformed();
    }//GEN-LAST:event_keystorePathButtonActionPerformed

    private void policyGetCertificateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_policyGetCertificateButtonActionPerformed
        handleGetCertificateButtonActionPerformed();
    }//GEN-LAST:event_policyGetCertificateButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel centerPanel;
    private javax.swing.JPanel centerTitlePanel;
    private javax.swing.JLabel certificatePswLabel;
    private javax.swing.JPasswordField certificatePswText;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JTextArea keystoreNotesArea;
    private javax.swing.JLabel keystoreNoteslabel;
    private javax.swing.JButton keystorePathButton;
    private javax.swing.JLabel keystorePathLabel;
    private javax.swing.JTextField keystorePathText;
    private javax.swing.JLabel keystorePswLabel;
    private javax.swing.JPasswordField keystorePswText;
    private javax.swing.JButton policyGetCertificateButton;
    private javax.swing.JLabel welcomeLabel;
    // End of variables declaration//GEN-END:variables


    private void handleKeystorePathButtonActionPerformed(){
        if (currentKeystoreDirecotory == null) {
            keystoreChooser.setCurrentDirectory(new File("."));
        }
        else {
            keystoreChooser.setCurrentDirectory(currentKeystoreDirecotory);
        }
        int returnValue = keystoreChooser.showOpenDialog(getRootPane());
        if (returnValue == JFileChooser.APPROVE_OPTION) {
            File keystoreFile = keystoreChooser.getSelectedFile();
            currentKeystoreDirecotory = keystoreChooser.getSelectedFile().getParentFile();
            keystorePathText.setText(keystoreFile.getAbsolutePath());
            keystorePathText.setBorder(javax.swing.BorderFactory.createLineBorder(
                    new java.awt.Color(0, 0, 0)));
        }
        validatePanelStatus();
    }

    private void handleGetCertificateButtonActionPerformed(){
        if (controller.recoverAccessRightsCapabilityX509Certificate(currentKeystoreDirecotory,
                keystorePswText.getPassword(), certificatePswText.getPassword())) {
            keystoreNotesArea.setText(controller.getX509CertificatePublicValuesToString());
            keystoreNotesArea.setCaretPosition(0);
        }
        validatePanelStatus();
    }

    private void checkKeystorePathDocument() {

        keystorePathText.getDocument().addDocumentListener(new DocumentListener() {

            public void insertUpdate(DocumentEvent e) {
                changeDelegationPathBorderColor(e);
            }

            public void removeUpdate(DocumentEvent e) {
                changeDelegationPathBorderColor(e);
            }

            public void changedUpdate(DocumentEvent e) {
                changeDelegationPathBorderColor(e);
            }

            private void changeDelegationPathBorderColor(DocumentEvent e) {
                String strKeystorePath = keystorePathText.getText();
                try {
                    File typedFile = new File(strKeystorePath);
                    if (!strKeystorePath.equals("")
                            && filterKeystore.accept(typedFile)) {

                        keystorePathText.setBorder(
                                javax.swing.BorderFactory.createLineBorder(
                                new java.awt.Color(0, 0, 0)));

                        currentKeystoreDirecotory = typedFile;

                        isKeystorePathOk = true;

                    } else {

                        keystorePathText.setBorder(
                                javax.swing.BorderFactory.createLineBorder(
                                new java.awt.Color(255, 0, 0)));

                        isKeystorePathOk = false;
                    }
                } catch (Exception ex) {
                    isKeystorePathOk = false;
                }

                policyGetCertificateButton.setEnabled(isKeystorePathOk
                        && isKeystorePswOPk && isCertificatePswOk);
            }
        });
    }

    private void checkKeystorePasswordDocument() {

        keystorePswText.getDocument().addDocumentListener(new DocumentListener() {

            public void insertUpdate(DocumentEvent e) {
                changeDelegationPathBorderColor(e);
            }

            public void removeUpdate(DocumentEvent e) {
                changeDelegationPathBorderColor(e);
            }

            public void changedUpdate(DocumentEvent e) {
                changeDelegationPathBorderColor(e);
            }

            private void changeDelegationPathBorderColor(DocumentEvent e) {
                char[] strKeystorePsw = keystorePswText.getPassword();
                if (strKeystorePsw.length > 0) {
                    keystorePswText.setBorder(
                            javax.swing.BorderFactory.createLineBorder(
                            new java.awt.Color(0, 0, 0)));
                    isKeystorePswOPk = true;
                } else {
                    keystorePswText.setBorder(
                            javax.swing.BorderFactory.createLineBorder(
                            new java.awt.Color(255, 0, 0)));
                    isKeystorePswOPk = false;
                }
                policyGetCertificateButton.setEnabled(isKeystorePswOPk
                        && isKeystorePathOk && isCertificatePswOk);
            }
        });
    }

    private void checkCertificatePasswordDocument() {

        certificatePswText.getDocument().addDocumentListener(new DocumentListener() {

            public void insertUpdate(DocumentEvent e) {
                changeDelegationPathBorderColor(e);
            }

            public void removeUpdate(DocumentEvent e) {
                changeDelegationPathBorderColor(e);
            }

            public void changedUpdate(DocumentEvent e) {
                changeDelegationPathBorderColor(e);
            }

            private void changeDelegationPathBorderColor(DocumentEvent e) {
                char[] strCertificatePsw = certificatePswText.getPassword();
                if (strCertificatePsw.length > 0) {
                    certificatePswText.setBorder(
                            javax.swing.BorderFactory.createLineBorder(
                            new java.awt.Color(0, 0, 0)));
                    isCertificatePswOk = true;
                } else {
                    certificatePswText.setBorder(
                            javax.swing.BorderFactory.createLineBorder(
                            new java.awt.Color(255, 0, 0)));
                    isCertificatePswOk = false;
                }
                policyGetCertificateButton.setEnabled(isCertificatePswOk
                        && isKeystorePathOk && isKeystorePswOPk);
            }
        });
    }

    public void validatePanelStatus() {
        boolean b = isKeystorePathOk && isKeystorePswOPk && isCertificatePswOk;
        policyGetCertificateButton.setEnabled(b);
    }
}
